import {defineStore} from 'pinia'
import {ref} from 'vue'
import type {LoginForm, UserInfo} from '@/types/user'
import {getUserInfo, login, logout} from '@/api/auth'
import {getToken, removeToken, setToken} from '@/utils/auth'
import {ElMessage} from 'element-plus'

export const useUserStore = defineStore('user', () => {
  // 状态
  const token = ref<string>(getToken() || '')
  const userInfo = ref<UserInfo | null>(null)
  const loading = ref(false)

  // 登录
  const loginAction = async (loginForm: LoginForm) => {
    try {
      loading.value = true
      const loginResponse = await login(loginForm)
      
      const { token: newToken, ...userInfoData } = loginResponse
      
      // 保存token
      token.value = newToken
      setToken(newToken)
      
      // 保存用户信息
      userInfo.value = {
        userId: userInfoData.userId,
        username: userInfoData.username,
        nickname: userInfoData.nickname,
        avatar: userInfoData.avatar,
        roleId: userInfoData.roleId,
        roleName: userInfoData.roleName,
        deptId: userInfoData.deptId,
        deptName: userInfoData.deptName,
        permissions: userInfoData.permissions || []
      }
      
      ElMessage.success('登录成功')
      return true
    } catch (error: any) {
      console.error('登录失败:', error)
      ElMessage.error(error.message || '登录失败，请检查网络连接')
      return false
    } finally {
      loading.value = false
    }
  }

  // 获取用户信息
  const getUserInfoAction = async () => {
    try {
      const userData = await getUserInfo()
      
      userInfo.value = {
        userId: userData.id || '',
        username: userData.username,
        nickname: userData.nickname || userData.username,
        avatar: userData.avatar || '',
        roleId: '1', // 默认角色ID
        roleName: '管理员', // 默认角色名
        deptId: '1', // 默认部门ID
        deptName: '技术部', // 默认部门名
        permissions: [] // 权限列表
      }
      return userInfo.value
    } catch (error: any) {
      console.error('获取用户信息失败:', error)
      throw error
    }
  }

  // 退出登录
  const logoutAction = async () => {
    try {
      await logout()
    } catch (error) {
      console.error('退出登录失败:', error)
    } finally {
      // 清除本地数据
      token.value = ''
      userInfo.value = null
      removeToken()
      ElMessage.success('退出登录成功')
    }
  }

  // 检查权限
  const hasPermission = (permission: string): boolean => {
    if (!userInfo.value || !userInfo.value.permissions) {
      return false
    }
    return userInfo.value.permissions.includes(permission)
  }

  // 检查角色
  const hasRole = (role: string): boolean => {
    if (!userInfo.value) {
      return false
    }
    return userInfo.value.roleName === role
  }

  return {
    // 状态
    token,
    userInfo,
    loading,
    
    // 方法
    login: loginAction,
    getUserInfo: getUserInfoAction,
    logout: logoutAction,
    hasPermission,
    hasRole
  }
})